package com.yexin.qingzhou.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yexin.qingzhou.common.Result;
import com.yexin.qingzhou.dto.LoginResponseDTO;
import com.yexin.qingzhou.dto.UserLoginDTO;
import com.yexin.qingzhou.dto.UserRegisterDTO;
import com.yexin.qingzhou.entity.User;
import com.yexin.qingzhou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserController {
    
    @Autowired
    private UserService userService;

    @PostMapping("/users/login")
    public Result<LoginResponseDTO> login(@Validated @RequestBody UserLoginDTO loginDTO) {
        log.info("用户登录: {}", loginDTO.getUsername());
        try {
            LoginResponseDTO response = userService.login(loginDTO);
            return Result.success(response);
        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/users/register")
    public Result<User> register(@Validated @RequestBody UserRegisterDTO registerDTO) {
        log.info("用户注册: {}", registerDTO.getUsername());
        User user = userService.register(registerDTO);
        return Result.success(user);
    }

    @GetMapping("/users/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    @GetMapping("/users")
    public Result<Page<User>> getUserList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return Result.success(userService.getUserList(pageNum, pageSize));
    }

    @PutMapping("/users")
    public Result<User> updateUser(@Validated @RequestBody User user) {
        return Result.success(userService.updateUser(user));
    }

    @DeleteMapping("/users/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success(null);
    }
} 